package com.singlemusic.controller;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.singlemusic.pojo.Artists;
import com.singlemusic.pojo.Tracks;
import com.singlemusic.service.impl.ArtistService;
import com.singlemusic.service.impl.TracksService;
import com.singlemusic.utils.FileUtils;

@Controller
@RequestMapping("/tracks")
public class TracksController {
	@Resource(name="artistService")
	private ArtistService artistService;
	
	@Resource(name="tracksService")
	private TracksService tracksService;
	
	@RequestMapping(value="/addTracks", method=RequestMethod.POST)
	public void addTracks(@ModelAttribute("tracks") Tracks tracks,
			@RequestParam(name="artistid") String artistid,
			@RequestParam(name="artisname") String artistname,
			@RequestParam(name="file") MultipartFile file,
			HttpServletRequest request){
		String path = request.getSession().getServletContext().getRealPath("data");
		String saveFolderPath = path+"/"+artistname+"/"+tracks.getTracksname();
		String fileName = file.getOriginalFilename();
		String savePath = "/"+artistname+"/"+tracks.getTracksname()+"/"+fileName;
		
		InputStream is = null;
		System.out.println(savePath);
		try {
			is = file.getInputStream();
		} catch (Exception e) {
			e.printStackTrace();
		}
		boolean flag = FileUtils.saveFile(is, saveFolderPath, fileName);
		if(flag=true){
			System.out.println("save success");
		}else{
			System.out.println("save failed");
		}
	}
	
	@ResponseBody
	@RequestMapping("/loadArtist")
	public List<Artists> loadArtist(@RequestParam(name="artistname") String artistname){
		List<Artists> list = new ArrayList<Artists>();
		String hql = "From Artists where artistname like(?)";
		String[] param={artistname+"%"};
		list = artistService.loadArtist(hql, param);
		
		return list;
	}
}
